# -*- coding: utf-8 -*-

from PyQt5.QtCore import QThread
from selenium import webdriver
from time import sleep
from os.path import exists
from os import remove
from pickle import dump, load
import requests
from selenium.webdriver.common.by import By


class Cookie(QThread):
    # sig = pyqtSignal(int)

    def __init__(self, user, passwd, parent=None):
        super().__init__(parent)
        self._user_ = user
        self._passwd_ = passwd

    def get_cookie(self):
        login_url = "https://passport.damai.cn/login"
        test_url = "https://bot.sannysoft.com"
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_experimental_option(
            "excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('lang=zh-CN,zh,zh-TW,en-US,en')
        chrome_options.add_argument("disable-blink-features=AutomationControlled")
        if not exists("cookies.pkl"):
            driver = webdriver.Chrome(chrome_options=chrome_options)
            driver.get(login_url)
            print("###请扫码登录###")
            while driver.title == '大麦登录':  # 等待扫码完成
                sleep(1)
                # 切换到iframe内容
                driver.switch_to.frame("alibaba-login-box")
                # 点击扫码登陆
                driver.find_element(By.XPATH, "/html/body/div/div/div[2]/div/form/div[1]/div[2]/input").send_keys(self._user_)
                driver.find_element(By.XPATH, "/html/body/div/div/div[2]/div/form/div[2]/div[2]/input").send_keys(self._passwd_)
                driver.find_element(By.XPATH, '//*[@id="login-form"]/div[4]/button').click()
                #driver.find_element_by_xpath("/html/body/div[1]/div/div[1]/div[3]").click()
                sleep(1)
            dump(driver.get_cookies(), open("cookies.pkl", "wb"))
            driver.quit()
            print("###Cookie保存成功###")

    def login(self):
        if not exists('cookies.pkl'):  # 如果不存在cookie.pkl,就获取一下
            self.get_cookie()
        print('###打开浏览器，进入大麦网###')
        # 设置不载入图片，提高刷新效率
        options = webdriver.ChromeOptions()
        prefs = {"profile.managed_default_content_settings.images":2} # 禁止加载图片
        options.add_experimental_option("prefs",prefs)
        driver = webdriver.Chrome(options=options)
        driver.get(self.target_url)
        driver.set_cookie()
        driver.refresh()
        driver.quit()
        # TODO:check login success
        # try:
